// import { useDispatch } from 'react-redux';
import { registerApi } from '../../api/user';
import { useNavigate } from 'react-router-dom';
import { Form, Input, Button, message } from 'antd';
import { useState } from 'react';

const Register = () => {
  const [isLoading, setIsLoading] = useState(false);

  const navigate = useNavigate();
  const [form] = Form.useForm();

  const onFinish = async (values: { username: string; password: string; confirmPassword: string }) => {
    setIsLoading(true);
    if (values.password !== values.confirmPassword) {
      message.error('密码与确认密码不一致');
      return;
    }
    try {
      const res:any = await registerApi(values);
      localStorage.setItem('token', res.token);
      message.success('注册成功');
      navigate('/login');
      setIsLoading(false);
    } catch (error) {
      setIsLoading(false);
      if (error instanceof Error) {
        message.error(error.message || '注册失败');
      }
    }
  };

  return (
    <div style={{ minHeight: '100vh', display: 'flex', justifyContent: 'center', alignItems: 'center', background: '#f8f9fa', padding: '20px' }}>
      <Form
        form={form}
        name="register"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ backgroundColor: 'white', padding: '40px', borderRadius: '12px', boxShadow: '0 4px 12px rgba(0,0,0,0.08)', maxWidth: '400px', width: '90%' }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="用户名"
          name="username"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          rules={[{ required: true, message: '请输入用户名！' }]}
        >
          <Input style={{ height: '40px', borderRadius: '8px', border: '1px solid #d9d9d9', padding: '0 12px' }} />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          rules={[{ required: true, message: '请输入密码！' }]}
        >
          <Input.Password style={{ height: '40px', borderRadius: '8px', border: '1px solid #d9d9d9', padding: '0 12px' }} />
        </Form.Item>

        <Form.Item
          label="确认密码"
          name="confirmPassword"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          rules={[{ required: true, message: '请确认密码！' }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit" loading={isLoading} style={{ width: '100%', height: '40px', borderRadius: '8px', fontSize: '16px' }}>
            注册
          </Button>
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="link" onClick={() => navigate('/login')}>
            去登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Register;